//
//  RegisterViewController.m
//  mytext
//
//  Created by wj on 16/6/6.
//  Copyright © 2016年 wj. All rights reserved.
//

#import "RegisterViewController.h"
#import "writePInfoViewController.h"

@interface RegisterViewController ()
{
    int _secondsCountDown;
    NSTimer* _countDownTimer;
    NSString * _yanZhenMa;
}


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *userTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *registerTop;
@property (weak, nonatomic) IBOutlet UIButton *regBtn;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _secondsCountDown = 60;
    self.view.backgroundColor = RGB(240, 239, 244);
    [self setUI];
    
//    [self getTuXingMakeCode];
}

-(void)timenFireMethod
{
    _secondsCountDown--;
    if (_secondsCountDown > 0)
    {
        [self.yzmBtn setTitle:[NSString stringWithFormat:@"%d s",_secondsCountDown] forState:UIControlStateNormal];
        self.yzmBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    }
    else
    {
        [_countDownTimer invalidate];
        _countDownTimer = nil;
        _secondsCountDown = 60;
        [self.yzmBtn setTitle:@"重新获取" forState:UIControlStateNormal];
        self.yzmBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.yzmBtn setEnabled:YES];
    }
    
//    NSLog(@"%d",_secondsCountDown);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setUI
{
    [self initNav];
    self.yzmBtn.layer.cornerRadius = 5;
    self.regBtn.layer.cornerRadius = 5;
    
    UIView *leftV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 9, 1)];
    self.userNameT.leftView = leftV;
    self.userNameT.leftViewMode = UITextFieldViewModeAlways;

    
    UIView *leftV1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 9, 1)];
    self.yzmT1.leftView = leftV1;
    self.yzmT1.leftViewMode = UITextFieldViewModeAlways;

    self.yzmT1.userInteractionEnabled = NO;
    
    UIView *leftV2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 9, 1)];
    self.singleMaT.leftView = leftV2;
    self.singleMaT.leftViewMode = UITextFieldViewModeAlways;

    
    UIView *leftV3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 9, 1)];
    self.passwordT.leftView = leftV3;
    self.passwordT.leftViewMode = UITextFieldViewModeAlways;

    
    
    self.userTop.constant = [FrameTool getToolY:140];
    self.registerTop.constant = [FrameTool getToolY:60];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(getTuXingMakeCode)];
    self.tuXingLabel.userInteractionEnabled = YES;
    [self.tuXingLabel addGestureRecognizer:tap];
    
}
/*设置导航栏*/
- (void)initNav
{
    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    
    UILabel * titleLable = [UILabel new];
    titleLable.frame = CGRectMake( 0, 20,ScreenWidth,44);
    titleLable.backgroundColor = RGB(242, 242, 242);
    titleLable.text = @"注册";
    titleLable.font = [UIFont systemFontOfSize:18];
    titleLable.textColor = [UIColor blackColor];
    titleLable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLable];
    
    UIImageView *leftView = [[UIImageView alloc]initWithFrame:CGRectMake(20,34, 10, 20)];
    leftView.image = [UIImage imageNamed:@"back-arrow"];
    leftView.userInteractionEnabled = YES;
    [self.view addSubview:leftView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(back)];
    [leftView addGestureRecognizer:tap];
    
    
}
/**返回**/
-(void)back
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
//发送验证码
- (IBAction)sendYzm:(id)sender
{
    if ([self valiMobile:self.userNameT.text] == nil)
    {
//        NSDictionary* dic = @{@"mobile":self.userNameT.text};
//        [[LJFNetworkingManager shareManager] POST:MAKECODEURL parameters:dic success:^(id returnData, int code, NSString *msg)
//         {
//             if (code == 1)
//             {
//                 [self.yzmBtn setEnabled:NO];
//                 _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timenFireMethod) userInfo:nil repeats:YES];
//                 
//                 NSLog(@"msg == %@",msg);
//                 _yanZhenMa = returnData;
//                 
//             }else
//             {
//                 NSLog(@"msg == %@",msg);
//                 [SVProgressHUD showErrorWithStatus:msg];
//             }
//         } failure:^(NSError *error)
//         {
//             
//         } showHUD:self.view];
        
        int y = (arc4random() % 5001) + 5000;
        self.yzmT1.text = [NSString stringWithFormat:@"%d",y];
        
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:[self valiMobile:self.yzmT1.text]];
    }
}

//注册
- (IBAction)regist:(UIButton *)sender
{
    if ([self valiMobile:self.userNameT.text] != nil) {
        [SVProgressHUD showErrorWithStatus:[self valiMobile:self.yzmT1.text]];
        return;
    }
    if (self.yzmT1.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入短信验证码"];
        return;
    }
    if (![self.yzmT1.text isEqualToString:@""]) {
        
    }else
    {
        [SVProgressHUD showErrorWithStatus:@"短信验证码输入有误"];
        return;
    }
//    if (self.yzmT2.text.length == 0) {
//        [SVProgressHUD showErrorWithStatus:@"请输入图形验证码"];
//        return;
//    }
    if (self.passwordT.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入密码"];
        return;
    }
    
    NSString * uuid = [[NSUUID UUID] UUIDString];
//    90268D24-F745-440D-BEB1-3655EB8DD1B5
    //保存一个UUID字符串到钥匙串：
//    CFUUIDRef uuid = CFUUIDCreate(NULL);assert(uuid != NULL);CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
//    [SSKeychain setPassword: [NSString stringWithFormat:@"%@", uuidStr]
//                 forService:@"com.yourapp.yourcompany"account:@"user"];
//    
//    //从钥匙串读取UUID：
//    NSString *retrieveuuid = [SSKeychain passwordForService:@"com.marrymarry.dabanwan"account:@"user"];
//    NSLog(@"retrieveuuid === %@",retrieveuuid);
    
    NSDictionary* dic = @{@"mobile":self.userNameT.text,@"password":self.passwordT.text,@"sessionkey":uuid,@"single_number":self.singleMaT.text};
    [[LJFNetworkingManager shareManager] POST:REGISTERURL parameters:dic success:^(id returnData, int code, NSString *msg)
     {
         if (code == 1)
         {
             NSLog(@"msg == %@",msg);
             NSMutableDictionary * newdic = [NSMutableDictionary new];
             NSMutableDictionary * changeDic = [NSMutableDictionary new];
             newdic = [NSMutableDictionary dictionaryWithDictionary:returnData];
             for (NSString*s in [newdic allKeys]) {
                 if ([newdic[s] isEqual:[NSNull null]]) {
                     [newdic setObject:@"" forKey:s];
                 }
             }
             [changeDic addEntriesFromDictionary:newdic];
             NSDictionary *finialDic = [NSDictionary new];
             finialDic = [NSDictionary dictionaryWithDictionary:changeDic];
             [Tools syncNSUserDeafaultsByKey:MY_NET_INFO_DIC withValue:(NSDictionary *)finialDic];
             NSLog(@"%@",finialDic[@"id"]);
             [Tools syncNSUserDeafaultsByKey:USERID withValue:finialDic[@"id"]];
             writePInfoViewController *writeInfoVC = [[UIStoryboard storyboardWithName:@"writePInfoViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"writePInfoViewController"];
             [self deleteFileWithStrName:@"headIMG2.jpg"];
             [self deleteFileWithStrName:@"mainIMG2.jpg"];
             [Tools syncNSUserDeafaultsByKey:@"userName" withValue:self.userNameT.text];
             [Tools syncNSUserDeafaultsByKey:@"password" withValue:self.passwordT.text];
             [Tools removeNSUserDeafaultsByKey:MY_BIGGEST_INFO_DIC];
//             writeInfoVC.isFromRegister = YES;
             [self.navigationController pushViewController:writeInfoVC animated:YES];
             
         }else
         {
             NSLog(@"msg == %@",msg);
             [SVProgressHUD showErrorWithStatus:msg];
         }
     } failure:^(NSError *error)
     {
         
     } showHUD:self.view];
    
    NSLog(@"点击了注册");
    
   
}




// 删除沙盒里的文件
-(void)deleteFileWithStrName:(NSString *)fileName {
    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //文件名
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (!blHave) {
        NSLog(@"no  have");
        return ;
    }else {
        NSLog(@" have");
        BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
        if (blDele) {
            NSLog(@"dele success");
        }else {
            NSLog(@"dele fail");
        }
        
    }
}




//登入
- (IBAction)login:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return @"手机号长度不是11位";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3)
        {
            return nil;
        }else{
            return @"请输入正确的*****号码";
        }
    }
    return nil;
}

//#pragma mark - 图形验证码
//- (void)getTuXingMakeCode
//{
//    [[LJFNetworkingManager shareManager] POST:TUXINGURL parameters:nil success:^(id returnData, int code, NSString *msg)
//     {
//         if (code == 200)
//         {
//             NSLog(@"msg == %@",msg);
//             
//             self.tuXingLabel.text = returnData;
//         }else
//         {
//             NSLog(@"msg == %@",msg);
//             [SVProgressHUD showErrorWithStatus:msg];
//         }
//     } failure:^(NSError *error)
//     {
//         
//     } showHUD:nil];
//    
//}


@end
